const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const { expressjwt: jwt } = require("express-jwt");
const { jwtSecretKey } = require("./config/JwtSecretKye");
const ScheduleTool = require("./utils/ScheduleTool.js");
const dayjs = require("dayjs");
const DB = require("./config/Sequelize.js");
const {createServer} = require('http')
const server = createServer(app)
const  websocket = require('./config/websocket.js')
websocket(server)

//设置跨域
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//鉴权中间件
app.use(
  jwt({ secret: jwtSecretKey, algorithms: ["HS256"] }).unless({
    path: [
      /^\/api\/user\/v1\/register/,//用户注册接口
      /^\/api\/user\/v1\/login/,//用户登录接口
      /^\/api\/user\/v1\/forget/,//忘记密码接口
      /^\/api\/notify\/v1/,//通知接口
      /^\/api\/wx_login\/v1/,//微信通知接口
      /^\/api\/banner\/v1/,//轮播图通知接口
      /^\/api\/teacher\/v1/,//讲师接口
      /^\/api\/product\/v1/,//课程接口
      /^\/api\/order\/v1\/latest/,//课程购买动态接口
      /^\/api\/comment\/v1\/page/,//评论列表
      /^\/api\/getPlayUrl\/v1/,//视频播放地址
    ],
  })
);

// 弹幕相关接口
const barrageRouter = require('./router/barrage.js')
app.use('/api/barrage/v1', barrageRouter)

// 视频播放相关接口
const getPlayUrlRouter = require('./router/getPlayUrlRouter.js')
app.use('/api/getPlayUrl/v1', getPlayUrlRouter)

// 通知相关接口
const notifyRouter = require('./router/notify.js')
app.use('/api/notify/v1', notifyRouter)

// 用户相关接口
const userRouter = require('./router/user.js')
app.use('/api/user/v1', userRouter)

// 微信相关接口
const wxLoginRouter = require('./router/wxLogin.js')
app.use('/api/wx_login/v1', wxLoginRouter)

// 轮播图相关接口
const bannerRouter = require('./router/banner.js')
app.use('/api/banner/v1', bannerRouter)

// 课程相关接口
const productRouter = require('./router/product.js')
app.use('/api/product/v1', productRouter)

// 讲师接口
const teacherRouter = require('./router/teacher');
app.use('/api/teacher/v1', teacherRouter);

// 订单接口
const Orderouter = require('./router/order');
app.use('/api/order/v1', Orderouter);

// 评论接口
const commentRouter = require('./router/comment');

app.use('/api/comment/v1', commentRouter);

// 每天凌晨2点更新统计昨天用户观看视频时长
ScheduleTool.dayJob(2, async()=> {
  //计算昨日的日期
  let yesterday = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
  //2.统计昨天有观看视频的用户，并且去 重
  let onlyRecord = await DB.DurationRecord.findAll({
    attributes: [[DB.sequelize.fn('DISTINCT', DB.sequelize.col('account_id')), 'account_id']],
    where:{gmt_modified: {[Op.gt]: yesterday}},
    raw: true
  })
  //根据用户id计算每个用户总观看时长
  let itemRecord = onlyRecord.map(async item => {
    item['duration'] = await DB.DurationRecord.sum('duration', {
      where: {accound_id: item.accoundId}
    })
    return item
  })
  //转成普通数组
  let itemRecordList = await Promise.all(itemRecord)
  //3.将数据插入到统计表中
  itemRecordList.forEach(async item => {
    await DB.Statistics.create({
      account_id: item.account_id,
      duration: item.duration,
      gmt_create: yesterday
    })
  })
  itemRecordList.forEach(async item => {
    await DB.Account.update({
      lear_time: item.duration
    },{
      where: {id: item.account_id}
    })
  })
})

//错误中间件
app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    return res.send({ code: -1, data: null, message: "请先登陆" });
  }
  return res.send({ code: -1, data: null, message: res.message });
});

server.listen("8081", () => {
  console.log("启动成功在8081");
});
